package com.softwareinlife.gae.queue;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;

@SuppressWarnings("serial")
public class CreateTask extends HttpServlet {
	private static final Logger _logger = Logger.getLogger(CreateTask.class
			.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String strCallResult = "";
		resp.setContentType("text/plain");
		try {
			// Queue queue = QueueFactory.getDefaultQueue();
			Queue queue = QueueFactory.getDefaultQueue();

			for (int i = 0; i < 100; i++) {
				TaskOptions opts = TaskOptions.Builder.withDefaults()
						.url("/taskrun").param("num", "" + i)
						.etaMillis(new Date().getTime() + (2000 * i))
						// .header("Host",
						// BackendServiceFactory.getBackendService().getBackendAddress("order-backend"))
						.method(Method.POST);

				queue.add(opts);

				System.out.println(i + " = " + new Date());

			}
			strCallResult = "Successfully created a Task in the Queue";

			resp.getWriter().println(strCallResult);
		} catch (Exception ex) {
			strCallResult = "Fail: " + ex.getMessage();
			resp.getWriter().println(strCallResult);
		}
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
		// String strCallResult = "";
		// resp.setContentType("text/plain");
		// try {
		// String strEmailId = req.getParameter("emailid");
		// _logger.info("Got a Signup Subscriber Request for Email ID : "
		// + strEmailId);
		// //
		// // PUT YOUR TASK CODE HERE
		// //
		// strCallResult = "SUCCESS: Subscriber Signup";
		// _logger.info(strCallResult);
		// resp.getWriter().println(strCallResult);
		// } catch (Exception ex) {
		// strCallResult = "FAIL: Subscriber Signup : " + ex.getMessage();
		// _logger.info(strCallResult);
		// resp.getWriter().println(strCallResult);
		// }
	}
}
